package win.larryzeal.c01.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

/**
 * Created by 张少昆 on 2017/11/18.
 */
public class RealmA implements Realm {
    @Override
    public String getName(){
        return "RealmA";
    }

    @Override
    public boolean supports(AuthenticationToken authenticationToken){
        return authenticationToken instanceof UsernamePasswordToken;
    }

    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException{
        //TODO 务必注意，这里就是上面支持的类型，否则不会执行到这一步
        String username = ((UsernamePasswordToken) authenticationToken).getUsername();
        String password = new String(((UsernamePasswordToken) authenticationToken).getPassword());

        if(!"zhang".equals(username)){
            throw new UnknownAccountException();
        }
        if(!"123".equals(password)){
            throw new IncorrectCredentialsException();
        }
        //返回认证信息（还可以返回鉴权信息，如SimpleAuthorizationInfo，鉴权信息包含了认证信息）。
        //如果返回鉴权信息，那可以添加role、permission信息！使用者拿到subject就可以判断有无相应权限了
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
